/**
 * 用户模块服务文件
 */

const db = require('../db/users');
const { getById } = require('../db/roles');
const md5 = require('md5-node');
const { secret, tokenExpired } = require('../config.json');
const { sign } = require('jsonwebtoken');

/**
 * 添加
 * @param {*} ctx 
 */
const add = async ctx => {
    try {
        const { body } = ctx.request;
        const { username, phone, role_id } = body;
        const result = await db.exists(username, phone);
        if (result?.username === username) {
            return ctx.body = {
                code: 0,
                msg: '已存在相同的用户名'
            }
        }
        if (result?.phone === phone) {
            return ctx.body = {
                code: 0,
                msg: '已存在相同的手机号'
            }
        }
        const role = await getById(role_id);
        if (!role) {
            return ctx.body = {
                code: 0,
                msg: '角色不存在'
            }
        }
        body.role_name = role.name;
        body.password = md5(body.password);
        await db.add(body);
        ctx.body = {
            code: 1,
            msg: '用户添加成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '用户添加失败'
        }
    }
}

/**
 * 修改
 * @param {*} ctx 
 */
const update = async ctx => {
    try {
        const { body } = ctx.request;
        const { id, role_id, phone } = body;
        const result = await db.exists(null, phone, id);
        if (result) {
            return ctx.body = {
                code: 0,
                msg: '已存在相同的手机号'
            }
        }
        const role = await getById(role_id);
        if (!role) {
            return ctx.body = {
                code: 0,
                msg: '角色不存在'
            }
        }
        body.role_name = role.name;
        await db.update(body);
        ctx.body = {
            code: 1,
            msg: '用户修改成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '用户修改失败'
        }
    }
}

/**
 * 更改状态
 * @param {*} ctx 
 */
const changeStatus = async ctx => {
    try {
        if (ctx.request.body.id == ctx.state.user.id) {
            return ctx.body = {
                code: 0,
                msg: '不能更改自己的状态'
            }
        }
        await db.changeStatus(ctx.request.body);
        ctx.body = {
            code: 1,
            msg: '状态变更成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '状态变更失败'
        }
    }
}

/**
 * 修改密码
 * @param {*} ctx 
 */
const updatePassword = async ctx => {
    try {
        const { id, password } = ctx.request.body;
        await db.updatePassword(id, md5(password));
        ctx.body = {
            code: 1,
            msg: '密码修改成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '密码修改失败'
        }
    }
}

/**
 * 删除用户
 * @param {*} ctx 
 */
const deleteUser = async ctx => {
    try {
        const { id } = ctx.request.params;
        if (id == ctx.state.user.id) {
            return ctx.body = {
                code: 0,
                msg: '无法删除当前登录用户'
            }
        }
        await db.deleteUser(id);
        ctx.body = {
            code: 1,
            msg: '用户删除成功'
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '用户删除失败'
        }
    }
}

/**
 * 搜索
 * @param {*} ctx 
 */
const search = async ctx => {
    try {
        const { rows: data, count } = await db.search(ctx.request.query);
        ctx.body = {
            code: 1,
            data,
            count
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '用户搜索失败'
        }
    }
}

/**
 * 登录
 */
const login = async ctx => {
    try {
        const { username, password } = ctx.request.body;
        const user = await db.getUserByUsername(username);
        if (!user) {
            return ctx.body = {
                code: 0,
                msg: '用户名不存在'
            }
        }
        if (user.status == 0) {
            return ctx.body = {
                code: 0,
                msg: '账号已被禁用'
            }
        }
        if (md5(password) !== user.password) {
            return ctx.body = {
                code: 0,
                msg: '密码错误'
            }
        }
        const { id } = user;
        const token = sign({ id, username }, secret, { expiresIn: tokenExpired });
        user.password = token;
        ctx.body = {
            code: 1,
            data: user
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '登录失败'
        }
    }
}

module.exports = {
    add,
    login,
    update,
    search,
    deleteUser,
    changeStatus,
    updatePassword,
}